﻿using BootstrapBlazor.Components;
using BPM.Web.Shared.Data;
using BPM.Web.Shared.Dependencies;
using BPM.Web.Shared.Extensions;

namespace BPM.Web.Shared.Service;

[Scoped(typeof(ISysOrgService))]
public class SysOrgService : BaseService, ISysOrgService
{
    private readonly IOrgClient _orgClient;
    public SysOrgService(IOrgClient orgClient, ToastService toast) : base(toast)
        => _orgClient = orgClient;

    public Task<QueryData<OrgOutput>> PageAsync(OrgPageInput input)
        => QueryAsync(_orgClient.PageAsync(input));

    public Task<List<OrgOutput>?> ListAsync(OrgListInput input)
        => QueryAsync<List<OrgOutput>>(_orgClient.ListAsync(input));
    public Task<bool> AddAsync(OrgOutput input)
        => ExecuteAsync(_orgClient.AddAsync(input.Adapt<OrgAddInput>()));

    public Task<bool> DeleteAsync(IEnumerable<OrgOutput> input)
        => DeleteAsync(input.Adapts<OrgOutput, DeleteOrgInput>().Select(x => _orgClient.DeleteAsync(x)));

    public Task<bool> EditAsync(OrgOutput input)
        => ExecuteAsync(_orgClient.EditAsync(input.Adapt<UpdateOrgInput>()));

    public Task<SysOrg?> DetailAsync(QueryOrgInput input)
        => QueryAsync(_orgClient.DetailAsync(input));

    public Task<List<OrgTreeNode>?> TreeAsync()
        => QueryAsync<List<OrgTreeNode>>(_orgClient.TreeAsync());

    public async Task<List<TreeItem>> GetTreeOrgsAsync()
        => (await TreeAsync()).BuildTree<OrgTreeNode, long>((x, r) =>
        {
            r.Key = x.Id;
            r.Text = x.Title;
            r.HasChildNode = x.Children.Any();
            r.IsCollapsed = x.Children.Any();
        });

    public async Task<IEnumerable<CascaderItem>> GetCascaderOrgsAsync()
        => (await TreeAsync()).BuildCascader<OrgTreeNode, long>((x, r) =>
        {
            r.Value = x.Id.ToString();
            r.Text = x.Title ?? string.Empty;
        });
}

